<template>
    <div class="updata-photo">
        <img class="img" :src="img" alt="哈哈" ref="image"/>
        <div class="toolbar">
            <div class="cancel" @click="$emit('close')">取消</div>
            <div class="confirm" @click="onConfirm">完成</div>
        </div>
    </div>

</template>

<script>
import { upUserPhotoAPI } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { onMounted, ref } from 'vue'
import { Toast } from 'vant'
export default {
  name: 'editPhoto',
  props: {
    img: {
      type: String,
      required: true
    }
  },
  setup (props, content) {
    const image = ref(null)
    const cropper = ref(null)
    const onConfirm = () => {
      // 获取裁切结果 getCroppedCanvas()获取裁切的文件对象
      cropper.value.getCroppedCanvas().toBlob(async (blob) => {
        // Content-Type	multipart/form-data 必须传递formData对象
        // Content-Type	application/json
        const formData = new FormData()
        formData.append('photo', blob)

        const { data } = await upUserPhotoAPI(formData)
        // 关闭弹层
        content.emit('close')
        // 更新视图
        content.emit('upPhoto', data.data.photo)
      })
      Toast.success('修改成功')
    }
    onMounted(() => {
      const img = image.value
      cropper.value = new Cropper(img, {
        viewMode: 1, // 查看模式 限制裁剪器在画布区域内
        dragMode: 'move', // 拖动模式
        aspectRatio: 1, // 截图的比例
        autoCropArea: 1, // 自动截取区域
        cropBoxMovable: false, // 截取区是否可以移动
        cropBoxResizable: false, // 截图区是否可以缩放
        background: false, // 是否显示透明底
        movable: true// 背景图是否能被拖动
      })
      // console.log(cropper)
    })
    return {
      image,
      onConfirm
    }
  }
}
</script>

<style scoped lang="less">
.updata-photo {
    background-color: #000;
    height: 100%;

    .toolbar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;

        .cancel,.confirm {
            width: 90px;
            height: 90px;
            font-size: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
        }
    }
}
.img {
    display: block;
    max-width: 100%;
}
</style>
